import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from './trpc/router';
import { createTRPCContext } from './trpc/context';
import { rechargeService } from './services/rechargeService';
import { payoutService } from './services/payoutService';
import { paymentMonitorService } from './services/paymentMonitorService';
import { PaymentChannel } from '@prisma/client';
import { Logger } from './utils/logger';

const app = new Hono();

// 中间件
app.use('*', logger());

// CORS 配置 - 从环境变量读取
app.use('*', cors({
  origin: '*',
  allowHeaders: ['*'],
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  credentials: true,
}));

// 健康检查端点
app.get('/health', (c) => {
  return c.json({ 
    status: 'ok', 
    timestamp: new Date().toISOString(),
    service: 'vue-turbo-stack-api'
  });
});

// TopPay 支付回调端点
app.post('/api/callback/toppay', async (c) => {
  try {
    Logger.info('收到TopPay支付回调', { ip: c.req.header('x-forwarded-for') || 'unknown' });
    
    const notification = await c.req.json();
    
    await rechargeService.handlePaymentNotification(PaymentChannel.TOPPAY, notification);
    
    // TopPay 要求返回 "SUCCESS" 字符串表示处理成功
    return c.text('SUCCESS');
  } catch (error) {
    Logger.error('TopPay回调处理失败', error);
    // 返回失败响应，让 TopPay 重试
    return c.text('FAIL', 500);
  }
});

// Pay668 支付回调端点
app.post('/api/callback/pay668', async (c) => {
  try {
    Logger.info('收到Pay668支付回调', { ip: c.req.header('x-forwarded-for') || 'unknown' });
    
    const notification = await c.req.json();
    
    await rechargeService.handlePaymentNotification(PaymentChannel.PAY668, notification);
    
    // Pay668 要求返回 "SUCCESS" 字符串表示处理成功
    return c.text('SUCCESS');
  } catch (error) {
    Logger.error('Pay668回调处理失败', error);
    // 返回失败响应，让 Pay668 重试
    return c.text('FAIL', 500);
  }
});

// TopPay 提现回调端点
app.post('/api/callback/toppay-payout', async (c) => {
  try {
    Logger.info('收到TopPay提现回调', { ip: c.req.header('x-forwarded-for') || 'unknown' });
    
    const notification = await c.req.json();
    
    // TODO: 实现提现回调处理逻辑
    Logger.info('TopPay提现回调数据', notification);
    
    return c.text('SUCCESS');
  } catch (error) {
    Logger.error('TopPay提现回调处理失败', error);
    return c.text('FAIL', 500);
  }
});

// Pay668 提现回调端点
app.post('/api/callback/pay668-payout', async (c) => {
  try {
    Logger.info('收到Pay668提现回调', { ip: c.req.header('x-forwarded-for') || 'unknown' });
    
    const notification = await c.req.json();
    
    // TODO: 实现提现回调处理逻辑
    Logger.info('Pay668提现回调数据', notification);
    
    return c.text('SUCCESS');
  } catch (error) {
    Logger.error('Pay668提现回调处理失败', error);
    return c.text('FAIL', 500);
  }
});

// LSPPAY 支付回调端点
app.post('/api/callback/lsppay', async (c) => {
  let notificationData: any = null;

  const normalizeNotification = (raw: Record<string, any>) => {
    const numericFields = [
      'amount',
      'state',
      'orderState',
      'createdAt',
      'successTime',
      'reqTime'
    ];

    for (const field of numericFields) {
      if (raw[field] !== undefined && raw[field] !== null && raw[field] !== '') {
        const value = Number(raw[field]);
        if (!Number.isNaN(value)) {
          raw[field] = value;
        }
      }
    }

    return raw;
  };

  try {
    const ip = c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
    Logger.info('收到LSPPAY支付回调', { ip });

    const contentType = c.req.header('content-type')?.toLowerCase() || '';

    try {
      if (contentType.includes('application/json')) {
        notificationData = await c.req.json();
      } else if (contentType.includes('application/x-www-form-urlencoded')) {
        const formData = await c.req.parseBody();
        notificationData = {};
        for (const [key, value] of Object.entries(formData)) {
          if (typeof value === 'string') {
            notificationData[key] = value;
          }
        }
      } else {
        const rawText = await c.req.text();
        try {
          notificationData = JSON.parse(rawText);
        } catch {
          const params = new URLSearchParams(rawText);
          notificationData = {};
          params.forEach((value, key) => {
            notificationData[key] = value;
          });
        }
      }

      notificationData = normalizeNotification(notificationData || {});

      Logger.info('LSPPAY回调数据解析成功', {
        ip,
        orderId: notificationData.mchOrderNo || 'unknown',
        payOrderId: notificationData.payOrderId || 'unknown',
        state: notificationData.state ?? notificationData.orderState ?? 'unknown',
        contentType
      });
    } catch (parseError) {
      Logger.error('LSPPAY回调数据解析失败', parseError, { ip, contentType });
      throw new Error('回调数据解析失败');
    }

    await rechargeService.handlePaymentNotification(PaymentChannel.LSPPAY, notificationData);

    Logger.info('LSPPAY回调处理成功', {
      ip,
      orderId: notificationData.mchOrderNo || 'unknown'
    });

    // LSPPAY 要求返回 "success" 字符串表示处理成功
    return c.text('success');
  } catch (error) {
    Logger.error('LSPPAY回调处理失败', error, {
      ip: c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown',
      orderId: notificationData?.mchOrderNo || 'unknown',
      notificationData: notificationData ? JSON.stringify(notificationData) : 'parse failed'
    });
    // 返回失败响应，让 LSPPAY 重试
    return c.text('fail', 500);
  }
});

// LSPPAY 代付回调端点
app.post('/api/callback/lsppay/payout', async (c) => {
  try {
    Logger.info('收到LSPPAY代付回调', { ip: c.req.header('x-forwarded-for') || 'unknown' });

    const notification = await c.req.json();
    Logger.info('LSPPAY代付回调数据', { notification });

    await payoutService.handlePayoutNotification(PaymentChannel.LSPPAY, notification);

    // LSPPAY 要求返回 "success" 字符串表示处理成功
    return c.text('success');
  } catch (error) {
    Logger.error('LSPPAY代付回调处理失败', error);
    // 返回失败响应，让 LSPPAY 重试
    return c.text('fail', 500);
  }
});

// NASKI 充值回调端点
app.post('/api/callback/naski', async (c) => {
  try {
    Logger.info('收到NASKI充值回调', { ip: c.req.header('x-forwarded-for') || 'unknown' });

    const notification = await c.req.json();
    Logger.info('NASKI充值回调数据', { notification });

    await rechargeService.handlePaymentNotification(PaymentChannel.NASKI, notification);

    // NASKI 要求返回 "SUCCESS" 字符串表示处理成功
    return c.text('SUCCESS');
  } catch (error) {
    Logger.error('NASKI充值回调处理失败', error);
    // 返回失败响应，让 NASKI 重试
    return c.text('FAIL', 500);
  }
});

// tRPC 路由
app.use('/trpc/*', async (c) => {
  return fetchRequestHandler({
    endpoint: '/trpc',
    req: c.req.raw,
    router: appRouter,
    createContext: () => createTRPCContext(c),
  });
});

// 404 处理
app.notFound((c) => {
  return c.json({ error: 'Not Found' }, 404);
});

// 错误处理
app.onError((err, c) => {
  console.error('Server error:', err);
  return c.json({ 
    error: 'Internal Server Error',
    message: err.message 
  }, 500);
});

const port = process.env.PORT || 3001;

// 初始化支付监控服务
Logger.info('初始化支付监控服务');
const monitorStatus = paymentMonitorService.getMonitoringStatus();
Logger.info(`支付监控服务初始化完成，当前活跃监控: ${monitorStatus.activeCount} 个`);

// 优雅关闭处理
process.on('SIGINT', () => {
  Logger.info('收到 SIGINT 信号，开始优雅关闭服务...');
  paymentMonitorService.cleanup();
  process.exit(0);
});

process.on('SIGTERM', () => {
  Logger.info('收到 SIGTERM 信号，开始优雅关闭服务...');
  paymentMonitorService.cleanup();
  process.exit(0);
});

console.log(`🚀 Server running on http://localhost:${port}`);
console.log(`📡 tRPC endpoint: http://localhost:${port}/trpc`);
console.log(`🏥 Health check: http://localhost:${port}/health`);
console.log(`🔄 Payment monitoring service initialized`);

export default {
  port,
  fetch: app.fetch,
};
